<?php

namespace wxml\controllers;

use common\libs\CommonController;
use wxml\models\product\AR\ProductAR;
use wxml\models\Weixin;
use Yii;
use yii\web\Controller;
use wxml\models\product\Product;

class ProductController extends CommonController {

    public $layout = false;

    public function actionIndex() {
        $isbn = Yii::$app->request->post("isbn");
        $product = new Product();
        $res = $product->fetchProduct($isbn);
        $json = json_decode($res, true);
        if($json['errorCode'] > 0 || count($json['products']) == 0) {
            $output = ['status' => 1, 'msg' => '未找到相关书籍'];
        } else {
            $output = ['status' => $json['errorCode'], 'data' => ['book' => array_reverse($json['products'])[0]]];
        }
        return json_encode($output);
    }

    public function actionCreate() {
        $book = Yii::$app->request->post('book');
        $accessToken = yii::$app->request->post('access_token');
        $user = Weixin::checkIsLogin($accessToken);
        if($user===false){
            return $this->ajaxResponseError('用户还未登录，请重新登录', -999);
        }
        $product = new Product();
        $res = $product->createProduct($book,$user);
        if($res) {
            return $this->ajaxResponseSuccess('发布成功');
        } else {
            return $this->ajaxResponseError($product->getErrMsg(), -1);
        }
    }

    public function actionList(){
        $filters=Yii::$app->request->post('filters');
        $orders=Yii::$app->request->post('orders');
        $offset=Yii::$app->request->post('offset');
        $limit=Yii::$app->request->post('limit');

        $product=new Product();
        $res = $product->getProductList($filters,$orders,$offset,$limit);
        if($res) {
            return $this->ajaxResponseSuccess($res);
        } else {
            return $this->ajaxResponseError($product->getErrMsg(), -1);
        }

    }

    public function actionDetail(){
        $product_id=Yii::$app->request->post('product_id');

        if(empty($product_id)){
            return $this->ajaxResponseError('商品不存在', -1);
        }
        $product=new Product();
        $res=$product->getProductDetail($product_id);
        if($res) {
            return $this->ajaxResponseSuccess($res);
        } else {
            return $this->ajaxResponseError($product->getErrMsg(), -1);
        }
    }

}
